package model;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class RepositorioMarca {

	
	EntityManagerFactory emf;
	EntityManager em;
	
	public RepositorioMarca(){
		emf = Persistence.createEntityManagerFactory("dbteste");
		em = emf.createEntityManager();
	}
	
	public void salvar(Marca marca){
		
		em.getTransaction().begin();
		em.merge(marca); //se o Objeto já existir no BD o Hibernate tentará atualizá-lo
		em.getTransaction().commit();
		emf.close();
		
	}
	
	public Marca buscarPorId (int id){
		
		em.getTransaction().begin();
		Marca marca = em.find(Marca.class, id);
		em.getTransaction().commit();
		emf.close();
		return marca;
		
	}
	
	public void remover (Marca marca){
		
		em.getTransaction().begin();
		em.remove(marca); 
		em.getTransaction().commit();
		emf.close();
	}
	
	@SuppressWarnings("unchecked")
	public List<Marca> listarTodos(){
		
		em.getTransaction().begin();
		Query consulta = em.createNamedQuery("SELECT a FROM Automovel a");
		List<Marca>  marca = consulta.getResultList();
		em.getTransaction().commit();
		emf.close();
		return marca;
	}
}
